package com.atguigu.gmall.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 封捷
 * @create-date: 2022/8/26 16:08
 */
@RestController
public class RedissonController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping("/redisson/incr/redis/data")
    public String doRedisDataAccess() {

        RLock lock = null;

        try {

            // 获取锁操作
            // 1、声明锁的 key
            String lockKey = "redisson:lock:key";

            // 2、得到锁对象
            lock = redissonClient.getLock(lockKey);

            // 3、加锁
            lock.lock();

            // 4、核心操作
            doRedisDataIncr();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            // 解锁操作
            if (lock != null) {
                lock.unlock();
            }

        }

        return "ok";
    }

    private void doRedisDataIncr() {

        // 声明在 Redis 中存储数据的 Key
        String dataKey = "test:lock:number";

        // 尝试从 Redis 服务器读取数值数据
        ValueOperations<String, String> operator = redisTemplate.opsForValue();

        String numberData = operator.get(dataKey);

        if (numberData == null) {
            // 如果该值为空，说明 Redis 中尚未存入数据
            numberData = "0";

            // 存入 Redis
            operator.set(dataKey, numberData);
        }

        // 执行累加操作
        Integer number = Integer.parseInt(numberData) + 1;

        operator.set(dataKey, String.valueOf(number));

    }

}
